package com.netty.server;

import com.nettryhomework.JsonDecoder;
import com.nettryhomework.JsonEncoder;
import com.nettryhomework.UserService;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

public class UserServerImpl implements UserService {
    @Override
    public String sayHello(String word) {
        System.out.println("调用成功---参数:" + word);
        return "调用成功---参数:" + word;
    }

    public static void startServer(String hostname,Integer port) throws InterruptedException {
        NioEventLoopGroup bossGroup = new NioEventLoopGroup();
        NioEventLoopGroup workerGroup = new NioEventLoopGroup();
        ServerBootstrap serverBootstrap = new ServerBootstrap();
        serverBootstrap.group(bossGroup,workerGroup)
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        ChannelPipeline pipeline = socketChannel.pipeline();
                        pipeline.addLast(new StringEncoder())
                                .addLast(new JsonDecoder())
                                .addLast(new UserServerHandler(new UserServerImpl()));
                    }
                });
        serverBootstrap.bind(hostname,port).sync();
        System.out.println("服务已启动...");
    }
}
